package cn.ibizlab.eam.core.eam_core.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.eam.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.eam.core.eam_core.domain.EMApply;
import cn.ibizlab.eam.core.eam_core.filter.EMApplySearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMApplyService;

import cn.ibizlab.eam.util.helper.CachedBeanCopier;
import cn.ibizlab.eam.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.eam.core.eam_core.mapper.EMApplyMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[外委申请] 服务对象接口实现
 */
@Slf4j
@Service("EMApplyServiceImpl")
public class EMApplyServiceImpl extends ServiceImpl<EMApplyMapper, EMApply> implements IEMApplyService {

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMEquipService emequipService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMObjectService emobjectService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFOACService emrfoacService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFOCAService emrfocaService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFODEService emrfodeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMRFOMOService emrfomoService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMServiceService emserviceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFTeamService pfteamService;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(EMApply et) {
        fillParentData(et);
        createIndexMajorEntityData(et);
        if(!this.retBool(this.baseMapper.insert(et))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmapplyid()), et);
        return true;
    }

    @Override
    @Transactional
    public void createBatch(List<EMApply> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list, batchSize);
    }

    @Override
    @Transactional
    public boolean update(EMApply et) {
        fillParentData(et);
        emwooriService.update(emapplyInheritMapping.toEmwoori(et));
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("emapplyid", et.getEmapplyid()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmapplyid()), et);
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<EMApply> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list, batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        emwooriService.remove(key);
        boolean result = removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public EMApply get(String key) {
        EMApply et = getById(key);
        if(et == null){
            et = new EMApply();
            et.setEmapplyid(key);
        }
        else {
        }
        return et;
    }

    @Override
    public EMApply getDraft(EMApply et) {
        fillParentData(et);
        return et;
    }

    @Override
    public boolean checkKey(EMApply et) {
        return (!ObjectUtils.isEmpty(et.getEmapplyid())) && (!Objects.isNull(this.getById(et.getEmapplyid())));
    }
    @Override
    @Transactional
    public EMApply confirm(EMApply et) {
         return et ;
    }

    @Override
    @Transactional
    public EMApply formUpdateByEmquipId(EMApply et) {
         return et ;
    }

    @Override
    @Transactional
    public EMApply rejected(EMApply et) {
         return et ;
    }

    @Override
    @Transactional
    public boolean save(EMApply et) {
        if(!saveOrUpdate(et)) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(EMApply et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? getProxyService().update(et) : getProxyService().create(et);
        }
    }

    @Override
    @Transactional
    public boolean saveBatch(Collection<EMApply> list) {
        list.forEach(item->fillParentData(item));
        List<EMApply> create = new ArrayList<>();
        List<EMApply> update = new ArrayList<>();
        for (EMApply et : list) {
            if (ObjectUtils.isEmpty(et.getEmapplyid()) || ObjectUtils.isEmpty(getById(et.getEmapplyid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<EMApply> list) {
        list.forEach(item->fillParentData(item));
        List<EMApply> create = new ArrayList<>();
        List<EMApply> update = new ArrayList<>();
        for (EMApply et : list) {
            if (ObjectUtils.isEmpty(et.getEmapplyid()) || ObjectUtils.isEmpty(getById(et.getEmapplyid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
    }

    @Override
    @Transactional
    public EMApply submit(EMApply et) {
         return et ;
    }


	@Override
    public List<EMApply> selectByEquipid(String emequipid) {
        return baseMapper.selectByEquipid(emequipid);
    }
    @Override
    public void removeByEquipid(String emequipid) {
        this.remove(new QueryWrapper<EMApply>().eq("equipid",emequipid));
    }

	@Override
    public List<EMApply> selectByObjid(String emobjectid) {
        return baseMapper.selectByObjid(emobjectid);
    }
    @Override
    public void removeByObjid(String emobjectid) {
        this.remove(new QueryWrapper<EMApply>().eq("objid",emobjectid));
    }

	@Override
    public List<EMApply> selectByRfoacid(String emrfoacid) {
        return baseMapper.selectByRfoacid(emrfoacid);
    }
    @Override
    public void removeByRfoacid(String emrfoacid) {
        this.remove(new QueryWrapper<EMApply>().eq("rfoacid",emrfoacid));
    }

	@Override
    public List<EMApply> selectByRfocaid(String emrfocaid) {
        return baseMapper.selectByRfocaid(emrfocaid);
    }
    @Override
    public void removeByRfocaid(String emrfocaid) {
        this.remove(new QueryWrapper<EMApply>().eq("rfocaid",emrfocaid));
    }

	@Override
    public List<EMApply> selectByRfodeid(String emrfodeid) {
        return baseMapper.selectByRfodeid(emrfodeid);
    }
    @Override
    public void removeByRfodeid(String emrfodeid) {
        this.remove(new QueryWrapper<EMApply>().eq("rfodeid",emrfodeid));
    }

	@Override
    public List<EMApply> selectByRfomoid(String emrfomoid) {
        return baseMapper.selectByRfomoid(emrfomoid);
    }
    @Override
    public void removeByRfomoid(String emrfomoid) {
        this.remove(new QueryWrapper<EMApply>().eq("rfomoid",emrfomoid));
    }

	@Override
    public List<EMApply> selectByRserviceid(String emserviceid) {
        return baseMapper.selectByRserviceid(emserviceid);
    }
    @Override
    public void removeByRserviceid(String emserviceid) {
        this.remove(new QueryWrapper<EMApply>().eq("rserviceid",emserviceid));
    }

	@Override
    public List<EMApply> selectByRteamid(String pfteamid) {
        return baseMapper.selectByRteamid(pfteamid);
    }
    @Override
    public void removeByRteamid(String pfteamid) {
        this.remove(new QueryWrapper<EMApply>().eq("rteamid",pfteamid));
    }


    /**
     * 查询集合 已完成
     */
    @Override
    public Page<EMApply> searchConfirmed(EMApplySearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMApply> pages=baseMapper.searchConfirmed(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMApply>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<EMApply> searchDefault(EMApplySearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMApply> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMApply>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 未提交
     */
    @Override
    public Page<EMApply> searchDraft(EMApplySearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMApply> pages=baseMapper.searchDraft(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMApply>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 待完成
     */
    @Override
    public Page<EMApply> searchToConfirm(EMApplySearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMApply> pages=baseMapper.searchToConfirm(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMApply>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMApply et){
        //实体关系[DER1N_EMAPPLY_EMEQUIP_EQUIPID]
        if(!ObjectUtils.isEmpty(et.getEquipid())){
            cn.ibizlab.eam.core.eam_core.domain.EMEquip equip=et.getEquip();
            if(ObjectUtils.isEmpty(equip)){
                cn.ibizlab.eam.core.eam_core.domain.EMEquip majorEntity=emequipService.get(et.getEquipid());
                et.setEquip(majorEntity);
                equip=majorEntity;
            }
            et.setEquipname(equip.getEquipinfo());
        }
        //实体关系[DER1N_EMAPPLY_EMOBJECT_OBJID]
        if(!ObjectUtils.isEmpty(et.getObjid())){
            cn.ibizlab.eam.core.eam_core.domain.EMObject obj=et.getObj();
            if(ObjectUtils.isEmpty(obj)){
                cn.ibizlab.eam.core.eam_core.domain.EMObject majorEntity=emobjectService.get(et.getObjid());
                et.setObj(majorEntity);
                obj=majorEntity;
            }
            et.setObjname(obj.getEmobjectname());
        }
        //实体关系[DER1N_EMAPPLY_EMRFOAC_RFOACID]
        if(!ObjectUtils.isEmpty(et.getRfoacid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFOAC rfoac=et.getRfoac();
            if(ObjectUtils.isEmpty(rfoac)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFOAC majorEntity=emrfoacService.get(et.getRfoacid());
                et.setRfoac(majorEntity);
                rfoac=majorEntity;
            }
            et.setRfoacname(rfoac.getEmrfoacname());
        }
        //实体关系[DER1N_EMAPPLY_EMRFOCA_RFOCAID]
        if(!ObjectUtils.isEmpty(et.getRfocaid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFOCA rfoca=et.getRfoca();
            if(ObjectUtils.isEmpty(rfoca)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFOCA majorEntity=emrfocaService.get(et.getRfocaid());
                et.setRfoca(majorEntity);
                rfoca=majorEntity;
            }
            et.setRfocaname(rfoca.getEmrfocaname());
        }
        //实体关系[DER1N_EMAPPLY_EMRFODE_RFODEID]
        if(!ObjectUtils.isEmpty(et.getRfodeid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFODE rfode=et.getRfode();
            if(ObjectUtils.isEmpty(rfode)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFODE majorEntity=emrfodeService.get(et.getRfodeid());
                et.setRfode(majorEntity);
                rfode=majorEntity;
            }
            et.setRfodename(rfode.getEmrfodename());
        }
        //实体关系[DER1N_EMAPPLY_EMRFOMO_RFOMOID]
        if(!ObjectUtils.isEmpty(et.getRfomoid())){
            cn.ibizlab.eam.core.eam_core.domain.EMRFOMO rfomo=et.getRfomo();
            if(ObjectUtils.isEmpty(rfomo)){
                cn.ibizlab.eam.core.eam_core.domain.EMRFOMO majorEntity=emrfomoService.get(et.getRfomoid());
                et.setRfomo(majorEntity);
                rfomo=majorEntity;
            }
            et.setRfomoname(rfomo.getEmrfomoname());
        }
        //实体关系[DER1N_EMAPPLY_EMSERVICE_RSERVICEID]
        if(!ObjectUtils.isEmpty(et.getRserviceid())){
            cn.ibizlab.eam.core.eam_core.domain.EMService rservice=et.getRservice();
            if(ObjectUtils.isEmpty(rservice)){
                cn.ibizlab.eam.core.eam_core.domain.EMService majorEntity=emserviceService.get(et.getRserviceid());
                et.setRservice(majorEntity);
                rservice=majorEntity;
            }
            et.setRservicename(rservice.getEmservicename());
        }
        //实体关系[DER1N_EMAPPLY_PFTEAM_RTEAMID]
        if(!ObjectUtils.isEmpty(et.getRteamid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFTeam rteam=et.getRteam();
            if(ObjectUtils.isEmpty(rteam)){
                cn.ibizlab.eam.core.eam_pf.domain.PFTeam majorEntity=pfteamService.get(et.getRteamid());
                et.setRteam(majorEntity);
                rteam=majorEntity;
            }
            et.setRteamname(rteam.getPfteamname());
        }
    }



    @Autowired
    cn.ibizlab.eam.core.eam_core.mapping.EMApplyInheritMapping emapplyInheritMapping;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWOORIService emwooriService;

    /**
     * 创建索引主实体数据
     * @param et
     */
    private void createIndexMajorEntityData(EMApply et){
        if(ObjectUtils.isEmpty(et.getEmapplyid()))
            et.setEmapplyid((String)et.getDefaultKey(true));
        cn.ibizlab.eam.core.eam_core.domain.EMWOORI emwoori =emapplyInheritMapping.toEmwoori(et);
        emwoori.set("emwooritype","APPLY");
        emwooriService.create(emwoori);
    }

    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<EMApply> getEmapplyByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<EMApply> getEmapplyByEntities(List<EMApply> entities) {
        List ids =new ArrayList();
        for(EMApply entity : entities){
            Serializable id=entity.getEmapplyid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0) {
            return this.listByIds(ids);
        }
        else {
            return entities;
        }
    }


    public IEMApplyService getProxyService() {
        return cn.ibizlab.eam.util.security.SpringContextHolder.getBean(this.getClass());
    }
}



